﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GCPUD.Autoprov.RemedyLib;

namespace GCPUD.AutoProv
{
    public partial class Form1 : Form
    {
        public static AutoProvSettings settings = new AutoProvSettings();
        public delegate void AddListItemDelegate(string item);
        public delegate void RemoveListItemDelegate(string item);
        public delegate void UpdateProblemListDelegate(List<ProvRequest> list);
        public delegate void ClearProblemListDelegate(List<ProvRequest> list);
        public delegate void UpdateServerStatusDelegate(bool isRunning);

        public UpdateProblemListDelegate updateProblemList;
        public ClearProblemListDelegate clearProblemList;
        public AddListItemDelegate addListItem;
        public RemoveListItemDelegate removeListItem;
        public UpdateServerStatusDelegate updateStatus;
        private ProvisioningWatcher watcher = new ProvisioningWatcher(); 
        TextBoxStreamWriter output = null;
        static public string FolderPath
        {
            get
            {
                string sPath = Process.GetCurrentProcess().MainModule.FileName;
                sPath = Path.GetDirectoryName(sPath);
                //sPath = Path.Combine(sPath, "Plugins\\Nobel\\");
                return sPath;
            }
        }

                
        public Form1()
        {
            
            InitializeComponent();
            output = new TextBoxStreamWriter(textBoxOutput);
            VeryifyHubProvFilesFolder(settings.provFileSaveDirectory);
            textBoxServer.Text = settings.provServer;
            textBoxPort.Text = settings.provPort.ToString();
            textBoxUser.Text = settings.provUser;
            textBoxPassword.Text = settings.provPassword;
            // Redirect the out Console stream  

            //Console.SetOut(output);

            //Console.WriteLine("Now redirecting output to the text box");  
            
           
        }

        private void VeryifyHubProvFilesFolder(string p)
        {
            if (!Directory.Exists(Path.GetDirectoryName(FolderPath+Path.DirectorySeparatorChar+p)))
            {
                Directory.CreateDirectory(p);
            }
         
        }
        ~Form1()
        { }

        private void StartProcess()
        {
            addListItem = AddListItemMethod;
            removeListItem = RemoveListItemMethod;
            updateProblemList = UpdateProblemListMethod;
            clearProblemList = ClearProblemListMethod;
            
            watcher.DataAdd += delegate(object sender, DataEventArgs e){addListItem(e.Data);};
            watcher.DataRemove += delegate(object sender, DataEventArgs e) { removeListItem(e.Data); };
            watcher.ClearProblems += delegate(object sender, ProblemsEventArgs e) { clearProblemList(e.ProvRequests); };
            watcher.UpdateProblems += delegate(object sender, ProblemsEventArgs e) { updateProblemList(e.ProvRequests); };
            //watcher.StatusChange += delegate(object sender, ServerEventArgs e) { updateStatus(e.Status); };
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += delegate(object sender, DoWorkEventArgs e) { ((ProvisioningWatcher)e.Argument).Start(settings); };
            bw.RunWorkerAsync(watcher); 
        }

    
        
        //public void UpdateServerStatusMethod(bool isRunning)
        //{
        //    if (radioButtonServerStatus.InvokeRequired)
        //    {
        //        BeginInvoke((MethodInvoker)(() => { UpdateServerStatus(isRunning); }));
        //        return;
        //    }
        //    UpdateServerStatus(isRunning);
        //}
        public void RemoveListItemMethod(string item)
        {
            if (listBoxNew.InvokeRequired)
            {
                BeginInvoke((MethodInvoker)(() => { RemoveListItemMethod(item); }));
                return;
            }
            RemoveList(item);
        }
        public void AddListItemMethod(string item)
        {
            if (listBoxNew.InvokeRequired)
            {
                BeginInvoke((MethodInvoker)(() => { AddListItemMethod(item); }));
                return;
            }
            AddList(item);
        }
        public void ClearProblemListMethod(List<ProvRequest> list)
        {
            if (listBoxProblems.InvokeRequired)
            {
                BeginInvoke((MethodInvoker)(() => { ClearProblemListMethod(list); }));
                return;
            }
            ClearProblemList(list);

        }
        public void UpdateProblemListMethod(List<ProvRequest> list)
        {
            if (listBoxProblems.InvokeRequired)
            {
                BeginInvoke((MethodInvoker)(() => { UpdateProblemListMethod(list); }));
                return;
            }
            UpdateProblemList(list);
        }

        //public void UpdateServerStatus(bool isRunning)
        //{
        //    radioButtonServerStatus.Checked = isRunning;
        //    if (isRunning) radioButtonServerStatus.Text = "Server Available";
        //    else radioButtonServerStatus.Text = "Server Unavailable";

        //}
        public void RemoveList(string item)
        {
            listBoxNew.Items.Remove(item);
        }
        public void AddList(string item)
        {
            listBoxNew.Items.Add(item);
            
        }
        public void ClearProblemList(List<ProvRequest> list)
        {
            treeViewContainer.Nodes.Clear();
            listBoxProblems.Items.Clear();
        }
        public void UpdateProblemList(List<ProvRequest> list)
        {
            listBoxProblems.Items.Clear();
            treeViewContainer.Nodes.Clear();
            foreach (ProvRequest provRequest in list)
            {
                TreeNode node = treeViewContainer.Nodes.Add(provRequest.Entry.RequestID);
                node.Tag = provRequest;
            }
            foreach (ProvRequest provRequest in list)
            {
                string itemEntry = provRequest.Entry.RequestID;

                listBoxProblems.Items.Add(itemEntry);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Instantiate the writer  
            output = new TextBoxStreamWriter(textBoxOutput);
            // Redirect the out Console stream  

            Console.SetOut(output);
            Console.WriteLine(DateTime.Now + ": Starting HubProv");
             
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartProcess();
            button1.Visible = false;
        }

        private void treeViewContainer_MouseMove(object sender, MouseEventArgs e)
        {
            // Get the node at the current mouse pointer location.
            TreeNode theNode = this.treeViewContainer.GetNodeAt(e.X, e.Y);

            // Set a ToolTip only if the mouse pointer is actually paused on a node.
            if ((theNode != null))
            {
                // Verify that the tag property is not "null".
                if (theNode.Tag != null)
                {
                    ProvRequest itemNode = (ProvRequest)theNode.Tag;
                    StringBuilder problemString = new StringBuilder();
                    foreach (String problemStringEntry in itemNode.Problems)
                    {
                        problemString.Append(problemStringEntry + System.Environment.NewLine);
                    }
                    // Change the ToolTip only if the pointer moved to a new node.
                    if (problemString.ToString() != this.toolTipContainer.GetToolTip(this.treeViewContainer))
                    {
                        
                        this.toolTipContainer.SetToolTip(this.treeViewContainer, problemString.ToString());
                    }
                }
                else
                {
                    this.toolTipContainer.SetToolTip(this.treeViewContainer, "");
                }
            }
            else     // Pointer is not over a node so clear the ToolTip.
            {
                this.toolTipContainer.SetToolTip(this.treeViewContainer, "");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            settings.provServer = textBoxServer.Text;
            settings.provPort = Int32.Parse(textBoxPort.Text);
            settings.provUser = textBoxUser.Text;
            settings.provPassword = textBoxPassword.Text;
            settings.Save();
        }

       



        
    }
}
